package com.wisdytech.linkdcs.factory.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.configuration.dao.ITtEqConfigurationDao;
import com.wisdytech.linkdcs.configuration.model.TtEqConfiguration;
import com.wisdytech.linkdcs.configuration.service.ITtEqConfigurationService;
import com.wisdytech.linkdcs.factory.dao.TmFactoryDao;
import com.wisdytech.linkdcs.factory.dao.TmLineOperationDao;
import com.wisdytech.linkdcs.factory.dao.TmProductionLineDao;
import com.wisdytech.linkdcs.factory.dao.TmShopLineDao;
import com.wisdytech.linkdcs.factory.model.Factory;
import com.wisdytech.linkdcs.factory.model.LineOperation;
import com.wisdytech.linkdcs.factory.model.ProductionLine;
import com.wisdytech.linkdcs.factory.model.ShopLine;
import com.wisdytech.linkdcs.factory.service.TmProductionLineService;
import com.wisdytech.linkdcs.system.dao.ISysOperationDao;
import com.wisdytech.linkdcs.system.model.SysOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * ClassName: TmFactoryServiceImpl
 * <p>
 * Description: 产线管理的业务实现类
 * </p>
 * <p>
 * Author: chenbin
 * </p>
 * <p>
 * Date: 2018年5月3日
 * </p>
 */
@Service("tmProductionLineService")
@Transactional
public class TmProductionLineServiceImpl  extends BaseService<TmProductionLineDao, ProductionLine> implements TmProductionLineService{

    /**
     * 注入产线管理dao
     */
	@Resource
	private TmProductionLineDao tmProductionLineDao;
    /**
     * 注入产线与工序管理dao
     */
	@Resource
	private TmLineOperationDao tmLineOperationDao;
    /**
     * 注入产线与车间关联管理dao
     */
	@Resource
	private TmShopLineDao tmShopLineDao;
	
	@Resource
	private ITtEqConfigurationService ttEqConfigurationService;

    @Resource
    private ITtEqConfigurationDao ttEqConfigurationDao;
	@Resource
	private ISysOperationDao iSysOperationDao;
	@Resource
	private TmFactoryDao tmFactoryDao;
	
	@Override
	public PageInfo<ProductionLine> listProductionLineByFilter(String lineCode, String lineName, Filter filter) {
        //查询所有产线--此方法通过sql语句查询
//		Map<String, Object> queryMap = new HashMap<String, Object>();
//        queryMap.put("lineCode", lineCode);
//        queryMap.put("lineName", lineName);
//        List<ProductionLine> lists =
//                super.beforeList(TmProductionLineDao.class, filter).listProductionLineByFilter(queryMap);
		EntityWrapper<ProductionLine> ew =new EntityWrapper<>();
		ew.like("LINE_CODE", lineCode).like("LINE_NAME", lineName).eq("del_flag", CommonConstants.DEL_FLAG);
        List<ProductionLine> lineLists = super.beforeList(TmProductionLineDao.class, filter).selectList(ew);
        //遍历每一个产线
		for(ProductionLine line : lineLists ) {
	        Factory factory = tmFactoryDao.selectById(line.getFactoryId());
	        line.setFactoryName(factory.getFactoryName());
			
			EntityWrapper<LineOperation> ew2 =new EntityWrapper<>();
			ew2.eq("LINE_ID", line.getPkId());
			//通过产线id查询关联对象
			List<LineOperation> opLineLists = tmLineOperationDao.selectList(ew2);
			//遍历每一个关联对象，
			List<String> opList = new ArrayList<>();
			for(LineOperation opLine : opLineLists) {
				SysOperation op = iSysOperationDao.selectById(opLine.getOpId());
				if (op!=null) {
					opList.add(op.getName());
				}
			}
			
			String opName = opList.toString();
			String opNameReal = opName.substring(1, opName.lastIndexOf("]"));
			line.setOperationName(opNameReal);
		}
        PageInfo<ProductionLine> productionLinePage = new PageInfo<>(lineLists);
        return productionLinePage;
	
	}

	@Override
	public boolean addProductionLine(ProductionLine productionLine, String loginName) {
        EntityWrapper<ProductionLine> ew =new EntityWrapper<>();
        //验证产线编号的唯一性
        List<ProductionLine> productionLineList;
        productionLineList = tmProductionLineDao.selectPage(new Page<ProductionLine>(1, 1), ew.eq("LINE_CODE", productionLine.getLineCode()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (!productionLineList.isEmpty()) {
        	throw new ServiceException("该产线编号被使用");
        }
        //生成产线id
        String pkId = BaseUtil.getUUID();
        //新增产线与工序（一个产线多个工序）
        for (int i = 0; i < productionLine.getOperationId().split(",").length; i++) {
        	LineOperation lineOperation = new LineOperation();
        	lineOperation.setPkId(BaseUtil.getUUID());
        	lineOperation.setLineId(pkId);
        	lineOperation.setOpId(productionLine.getOperationId().split(",")[i]);
            lineOperation.setCreateUser(loginName);
            lineOperation.setCreateDate(new Date());
            lineOperation.setDelFlag(CommonConstants.DEL_FLAG);
            int lineOperationCount =tmLineOperationDao.insert(lineOperation);
            if (lineOperationCount<=0){
                throw new ServiceException("新增产线与工序关联失败");
            }
        }
        //新增产线
        productionLine.setPkId(pkId);
        productionLine.setCreateUser(loginName);
        productionLine.setCreateDate(new Date());
        productionLine.setDelFlag(CommonConstants.DEL_FLAG);
        int productionLineCount =tmProductionLineDao.insert(productionLine);
        if (productionLineCount<=0){
            throw new ServiceException("新增产线失败");
        }
		return true;
	}

	@Override
	public boolean updateProductionLine(ProductionLine productionLine, String loginName) {
        EntityWrapper<ProductionLine> ew =new EntityWrapper<>();
        //验证产线编号的唯一性
        List<ProductionLine> productionLineList;
        productionLineList = tmProductionLineDao.selectPage(new Page<ProductionLine>(1, 1), ew.eq("LINE_CODE", productionLine.getLineCode()).ne("pk_id", productionLine.getPkId()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (!productionLineList.isEmpty()) {
        	throw new ServiceException("该产线编号被使用");
        }
    	//先删除产线与工序关联
    	EntityWrapper<LineOperation> ew1 =new EntityWrapper<>();
    	ew1.eq("LINE_ID", productionLine.getPkId());
        tmLineOperationDao.delete(ew1);
        //再新增产线与工序（一个产线多个工序）
        for (int i = 0; i < productionLine.getOperationId().split(",").length; i++) {
        	LineOperation lineOperation = new LineOperation();
        	lineOperation.setPkId(BaseUtil.getUUID());
        	lineOperation.setOpId(productionLine.getOperationId().split(",")[i]);
        	lineOperation.setLineId(productionLine.getPkId());
            lineOperation.setCreateUser(loginName);
            lineOperation.setCreateDate(new Date());
            lineOperation.setDelFlag(CommonConstants.DEL_FLAG);
            int lineOperationCount =tmLineOperationDao.insert(lineOperation);
            if (lineOperationCount<=0){
                throw new ServiceException("新增产线与工序关联失败");
            }
        }
        //修改产线
        productionLine.setUpdateUser(loginName);
        productionLine.setUpdateDate(new Date());
        int productionLineCount =tmProductionLineDao.updateLineById(productionLine);
        if (productionLineCount<=0){
            throw new ServiceException("新增产线失败");
        }
		return true;
	}

	@Override
	public boolean delProductionLineById(String id) {
		String[] ids = id.split(",");
		
		for(String pkId : ids) {
			//通过pkid查询是否关联车间
			EntityWrapper<ShopLine> ew1 =new EntityWrapper<>();
			ew1.eq("LINE_ID", pkId);
			int count = tmShopLineDao.selectCount(ew1);
			if(count>0) {
				throw new ServiceException("所选记录中存在“车间”");
			}
			
            //通过产线的id查询所有产线组态图
            EntityWrapper<TtEqConfiguration> ew = new EntityWrapper<>();
            ew.eq("del_flag", CommonConstants.DEL_FLAG).eq("location_id", pkId).eq("type", "2");
            int num = this.ttEqConfigurationDao.selectCount(ew);
            if(num>0) {
            	throw new ServiceException("所选记录中存在组态图关联");
            }
		}
        for (String pkId : ids) {
        	//删除产线与工序关联
        	EntityWrapper<LineOperation> ew1 =new EntityWrapper<>();
        	ew1.eq("LINE_ID", pkId);
            tmLineOperationDao.delete(ew1);

            //删除产线(假删除，改变状态)
            ProductionLine line = new ProductionLine();
            line.setPkId(pkId);
            line.setDelFlag(CommonConstants.DEL_FLAG_TRUE);
            int count =tmProductionLineDao.updateById(line); 
            if (count <= 0){
                throw new ServiceException("删除产线失败");
            }
        }
        return true;
	}

	@Override
	public ProductionLine getProductById(String pkId) {
		if(StringUtils.isBlank(pkId)) {
			return null;
		}
		ProductionLine line = tmProductionLineDao.selectById(pkId);
		if(line!=null) {
			Factory factory = tmFactoryDao.selectById(line.getFactoryId());
	        line.setFactoryName(factory.getFactoryName());
		}
		
		EntityWrapper<LineOperation> ew2 =new EntityWrapper<>();
		ew2.eq("LINE_ID", line.getPkId());
		//通过产线id查询关联对象
		List<LineOperation> opLineLists = tmLineOperationDao.selectList(ew2);
		//遍历每一个关联对象，
		List<String> opListName = new ArrayList<>();
		List<String> opListId = new ArrayList<>();
		for(LineOperation opLine : opLineLists) {
			SysOperation op = iSysOperationDao.selectById(opLine.getOpId());
			if(op!=null) {
				opListName.add(op.getName());
				opListId.add(op.getPkId());
			}

		}
		
		String opName = opListName.toString();
		String opNameReal = opName.substring(1, opName.lastIndexOf("]"));
		String ids = "";
		for(String id : opListId) {
			ids = ids +","+id;
		}
		// StringIndexOutOfBoundsException check
		if (ids.length()>1) {
			String opIdReal = ids.substring(1);
			line.setOperationId(opIdReal);
		}
		line.setOperationName(opNameReal);
		return line;
	}

	@Override
	public List<ProductionLine> listAllProduct(String search) {
        EntityWrapper<ProductionLine> ew = new EntityWrapper<>();
        ew.eq("DEL_FLAG", CommonConstants.DEL_FLAG).like("LINE_NAME",search);
        return tmProductionLineDao.selectList(ew);
	}

    @Override
    public List<ProductionLine> listAllLine(String factoryId) {
        EntityWrapper<ProductionLine> ew = new EntityWrapper<>();
        ew.setSqlSelect("pk_id","line_code","line_name");
        ew.eq("del_flag",CommonConstants.DEL_FLAG);
	    if(StringUtils.isNotBlank(factoryId)) {
            ew.eq("factory_id",factoryId);
        }
        return tmProductionLineDao.selectList(ew);
    }
}
